# -*- coding: utf-8 -*-

"""
# @Time    : 2022/5/11 0011 15:12
# @Author  : Silva
# @File    : spider_proxy.py
"""
import time
import random
import threading
import requests
import logging

lock = threading.Lock()
proxy_list = []
expire_time = 30
curent_time = time.time()



def bind_ip_to_whitelist(bind_api, bind_json):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36',
        'Content-Type': 'application/json'
    }
    rsp = requests.post(bind_api, headers=headers, json=bind_json)
    return rsp.json()

def get_proxies(proxy_api):
    '''
    获取第三方代理
    :return: proxy_list
    API Example:
        {
            "code": 0,
            "success": true,
            "msg": "请求成功",
            "request_ip": "61.140.233.51",
            "data": [
                {
                    "ip": "43.134.173.122",
                    "port": 7600
                },
                {
                    "ip": "43.134.173.122",
                    "port": 7599
                }
            ]
        }

    '''
    def get_web_proxy():
        __list = []
        rsp = requests.get(proxy_api).json()
        for item in rsp.get('data', []):
            ip_port = "https://{0}:{1}".format(item['ip'], item['port'])
            __list.append(ip_port)
        return __list

    global proxy_list
    global curent_time
    if not proxy_list or time.time() - curent_time > expire_time:
        lock.acquire()
        try:
            proxy_list = get_web_proxy()
        except:
            try:
                time.sleep(1)
                proxy_list = get_web_proxy()
            except Exception as e:
                lock.release()
                print('获取代理出错：{}'.format(e))
                return None
        lock.release()
        curent_time = time.time()
        return random.choice(proxy_list)
    else:
        return random.choice(proxy_list)

if __name__ == '__main__':
    proxy_api = 'http://api.proxy.ipidea.io/getProxyIp?num=20&tag=static_balance&return_type=json&lb=1&sb=0&flow=1&protocol=http'
    rsp = requests.get(proxy_api)
    print(rsp.json())

